package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.util.SMSUtils;
import com.itheima.reggie.util.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public R<User> login(@RequestBody Map<String,String> map, HttpSession session){
        String phone = map.get("phone");
        String userCode = map.get("code");
        //String sessionCode = (String) session.getAttribute(phone);
        //从缓存里获取验证码:
        String sessionCode = (String) redisTemplate.opsForValue().get(phone);

        User loginUser = userService.Login(phone, userCode, sessionCode);

        if (loginUser!= null) {
            session.setAttribute("user",loginUser.getId());
            //session.removeAttribute(phone);
            //将缓存的验证码删除
            redisTemplate.delete(phone);
            return R.success(loginUser);

        }
        return R.error("登录失败");


    }

        //处理发送短信的请求
        @PostMapping("/sendMsg")
        public R<String> sendMsg(@RequestBody User user, HttpSession session){
            //1.接收手机号封装User对象
            //2.生成4位手机验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            System.out.println("验证码："+code);
            //3.发送手机验证码
            //SMSUtils.sendMessage("黑马旅游网","SMS_198917972",user.getPhone(),code);
            //4.将生成的验证码存储到session中（手机号作为key，验证码作为value）
            //session.setAttribute(user.getPhone(),code);
            //验证码存储到缓存中并且是指过期时间5分钟
            redisTemplate.opsForValue().set(user.getPhone(),code,300, TimeUnit.SECONDS);

            //5.返回数据，输出成功
            return R.success("发送验证码短信成功!");
        }

}
